package com.bitejiuyeke.job_publish.service.impl;

import com.bitejiuyeke.job_publish.common.AppResult;
import com.bitejiuyeke.job_publish.common.PageResult;
import com.bitejiuyeke.job_publish.common.ResultCode;
import com.bitejiuyeke.job_publish.dao.SendRecordMapper;
import com.bitejiuyeke.job_publish.enums.DeleteStateEnum;
import com.bitejiuyeke.job_publish.enums.JobStateEnum;
import com.bitejiuyeke.job_publish.enums.SendRecordStateEnum;
import com.bitejiuyeke.job_publish.exception.ApplicationException;
import com.bitejiuyeke.job_publish.model.Job;
import com.bitejiuyeke.job_publish.model.Major;
import com.bitejiuyeke.job_publish.model.SendRecord;
import com.bitejiuyeke.job_publish.model.User;
import com.bitejiuyeke.job_publish.service.IJobService;
import com.bitejiuyeke.job_publish.service.IMajorService;
import com.bitejiuyeke.job_publish.service.ISendRecordService;
import com.bitejiuyeke.job_publish.service.IUserService;
import com.bitejiuyeke.job_publish.utils.StringUtils;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

/**
 * @Author 比特就业课
 */
@Slf4j
@Service
public class SendRecordServiceImpl implements ISendRecordService {

    @Resource
    private SendRecordMapper mapper;
    @Resource
    private IUserService userService;
    @Resource
    private IJobService jobService;
    @Resource
    private IMajorService majorService;

    @Override
    public void create(SendRecord record) {
        // 校验
        if (record == null || record.getUserId() == null || record.getUserId() <= 0
                || record.getJobId() == null || record.getJobId() <= 0) {
            log.warn("新增投递记录失败. " + ResultCode.FAILED_CREATE);
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_CREATE));
        }

        // 校验职位
        Job job = jobService.selectById(record.getJobId());
        if (job == null) {
            log.warn("添加投递记录失败. " + ResultCode.FAILED_JOB_NOT_EXISTS);
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_JOB_NOT_EXISTS));
        }
        if (JobStateEnum.valueOf(job.getState()) != JobStateEnum.RELEASED) {
            log.warn("添加投递记录失败. " + ResultCode.FAILED_JOB_NOT_RELEASED);
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_JOB_NOT_RELEASED));
        }
        // 校验投递用户不能是发布者
        if (job.getUserId() == record.getUserId()) {
            log.warn("添加投递记录失败. 不能投递自己发布的职位. userId = " + record.getUserId());
            throw new ApplicationException(AppResult.failed("不能投递自己发布的职位"));
        }
        // 用户是否存在
        User user = userService.selectById(record.getUserId());
        if (user == null) {
            log.warn("添加投递记录失败. " + ResultCode.FAILED_USER_NOT_EXISTS);
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_USER_NOT_EXISTS));
        }
        // 写入记录
        SendRecord sendRecord = new SendRecord();
        sendRecord.setUserId(record.getUserId());
        sendRecord.setJobId(record.getJobId());
        sendRecord.setReceiveUserId(job.getUserId());
        sendRecord.setState((byte) SendRecordStateEnum.POSTED.getCode());
        sendRecord.setDeleteState((byte) DeleteStateEnum.NORMAL.getCode());
        Date now = new Date();
        sendRecord.setCreateTime(now);
        sendRecord.setUpdateTime(now);
        int row = mapper.insertSelective(sendRecord);
        if (row != 1) {
            log.warn("添加投递记录失败. " + ResultCode.ERROR_SERVICES);
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_CREATE));
        }
        // 更新用户投递数
        userService.addSendCount(record.getUserId(), 1);
        // 更新职位投递数
        jobService.addReceiveCount(record.getJobId(), 1);
        log.info("添加投递记录成功. userId = {}, jobId = {}.", record.getUserId(), record.getJobId());
    }

    @Override
    public SendRecord selectById(Long id) {
        // 校验
        if (id == null || id <= 0) {
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        // 查询数据
        SendRecord record = mapper.selectByPrimaryKey(id);
        if (record == null || DeleteStateEnum.valueOf(record.getDeleteState()) == DeleteStateEnum.DELETED) {
            return null;
        }
        // 设置用户和职位信息
        User sendUser = userService.selectById(record.getUserId());
        record.setSendUser(sendUser);
        User receiveUser = userService.selectById(record.getReceiveUserId());
        record.setReceiveUser(receiveUser);
        Job job = jobService.selectById(record.getJobId());
        record.setJob(job);
        // 返回结果
        return record;
    }

    @Override
    public void modifyState(SendRecord record) {
        // 校验
        if (record.getId() == null || record.getId() <= 0 || record.getState() == null
        || SendRecordStateEnum.valueOf(record.getState()) == null
        || record.getReceiveUserId() == null || record.getReceiveUserId() <= 0) {
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        SendRecordStateEnum stateEnum = SendRecordStateEnum.valueOf(record.getState());
        // 获取投递记录对象
        SendRecord sendRecord = selectById(record.getId());
        if (sendRecord == null) {
            log.warn("设置投递状态失败. " + ResultCode.FAILED_NOT_EXISTS);
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_NOT_EXISTS));
        }
        // 是否发布者
        if (sendRecord.getReceiveUserId() != record.getReceiveUserId()) {
            log.warn("设置投递状态失败. " + ResultCode.FAILED_NOT_PERMISSION);
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_NOT_PERMISSION));
        }
        // 不能回退设置
        if (stateEnum.getCode() <= sendRecord.getState()) {
            log.warn("不能回退投递记录状态. recordId = {}", sendRecord.getId());
            throw new ApplicationException(AppResult.failed("不能回退投递记录状态."));
        }
        // 设置状态
        SendRecord update = new SendRecord();
        update.setId(sendRecord.getId());
        update.setState((byte) stateEnum.getCode());
        Date now = new Date();
        // 设置第一次已读时间
        if (stateEnum == SendRecordStateEnum.READ) {
            update.setReadTime(now);
        }
        // 备注信息
        if (!StringUtils.isEmpty(record.getRemark())) {
            update.setRemark(record.getRemark());
        }
        update.setUpdateTime(now);
        // 更新
        int row = mapper.updateByPrimaryKeySelective(update);
        if (row != 1) {
            log.warn("设置投递状态失败. " + ResultCode.ERROR_SERVICES);
            throw new ApplicationException(AppResult.failed("设置投递状态失败."));
        }

        log.info("更新投递状态成功.");

    }

    @Override
    public int selectTotalByReceiveUser(SendRecord record) {
        // 校验
        if (record == null || record.getPageSize() == null || record.getOffset() == null || record.getReceiveUserId() == null) {
            log.info("获取接收到的投递总数失败. " + ResultCode.FAILED_PARAMS_VALIDATE);
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        // 查询
        int totalRecord = mapper.selectTotalByReceiveUser(record);
        return totalRecord;
    }

    @Override
    public PageResult<SendRecord> selectPageByReceiveUser(SendRecord record) {
        // 获取总数
        int totalRecord = selectTotalByReceiveUser(record);
        // 分页结果对象
        PageResult<SendRecord> pageResult = new PageResult<>(record.getPageNum(), record.getPageSize(),
                totalRecord);
        // 分页数据列表
        List<SendRecord> list = mapper.selectPageByReceiveUser(record);
        pageResult.setRows(list);
        if (list != null) {
            for (SendRecord sendRecord: list) {
                // 设置专业
                User sendUser = sendRecord.getSendUser();
                Major major = majorService.selectDetailsById(sendUser.getMajorId());
                sendUser.setMajor(major);
                // 处理简介长度
                if (!StringUtils.isEmpty(sendUser.getRemark()) && sendUser.getRemark().length() > 100) {
                    sendUser.setRemark(sendUser.getRemark().substring(0, 100) + "...");
                }

                // 当前状态
                SendRecordStateEnum stateEnum = SendRecordStateEnum.valueOf(sendRecord.getState());
                // 已投递状态更新为已读
                SendRecord update = new SendRecord();
                update.setState((byte) SendRecordStateEnum.READ.getCode());
                Date date = new Date();
                update.setUpdateTime(date);
                update.setReadTime(date);
                // 更新
                if (stateEnum == SendRecordStateEnum.POSTED) {
                    update.setId(sendRecord.getId());
                    mapper.updateByPrimaryKeySelective(update);
                }
            }
        }

        // 返回结果
        return pageResult;
    }

    @Override
    public int selectTotalByUser(SendRecord record) {
        // 校验
        if (record == null || record.getPageSize() == null || record.getOffset() == null || record.getUserId() == null) {
            log.info("获取用户投递总数失败. " + ResultCode.FAILED_PARAMS_VALIDATE);
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        // 查询
        int totalRecord = mapper.selectTotalByUser(record);
        return totalRecord;
    }

    @Override
    public PageResult<SendRecord> selectPageByUser(SendRecord record) {
        // 获取总数
        int totalRecord = selectTotalByUser(record);
        // 分页结果对象
        PageResult<SendRecord> pageResult = new PageResult<>(record.getPageNum(), record.getPageSize(),
                totalRecord);
        // 分页数据列表
        List<SendRecord> list = mapper.selectPageByUser(record);
        pageResult.setRows(list);
        // 返回结果
        return pageResult;
    }

    @Override
    public int selectTotalByJob(SendRecord record) {
        // 校验
        if (record == null || record.getPageSize() == null || record.getOffset() == null) {
            log.info("获取职位下投递总数失败. " + ResultCode.FAILED_PARAMS_VALIDATE);
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        // 查询
        int totalRecord = mapper.selectTotalByJob(record);
        return totalRecord;
    }

    @Override
    public PageResult<SendRecord> selectPageByJob(SendRecord record) {
        // 获取总数
        int totalRecord = selectTotalByJob(record);
        // 分页结果对象
        PageResult<SendRecord> pageResult = new PageResult<>(record.getPageNum(), record.getPageSize(),
                totalRecord);
        // 分页数据列表
        List<SendRecord> list = mapper.selectPageByJob(record);
        pageResult.setRows(list);
        // 返回结果
        return pageResult;
    }
}
